import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

public class JDBCUtil {

    private static Properties p = null;

    private JDBCUtil(){}

    static {
        try{
            //1.初始化驱动类，在初始化的时候通过静态代码块中的java.sql.DriverManager.registerDriver(new Driver())注册驱动
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            InputStream inputStream = loader.getResourceAsStream("db.properties");
            p = new Properties();
            p.load(inputStream);
            Class.forName(p.getProperty("driverClassName"));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static Connection getConnection(){
        try{
            //2.获取数据库连接
            return DriverManager.getConnection(p.getProperty("url"),p.getProperty("username"),p.getProperty("password"));
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static void close(ResultSet rs, Statement st, Connection conn){
        //释放资源
        try{
            if(rs != null){
                rs.close();
            }

            if (st != null){
                st.close();
            }

            if(conn!=null){
                conn.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


}
